# -*-coding:utf-8 -*-

"""
# File       : pydexe.py
# Time       ：2023-03-14 10:32
# Author     ：baiya
# version    ：python 3.9.13
# Description：QQ:164846802
"""
import os
import shutil
import re
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("--name", type=str, help="请输入入口函数名称",default="mainfun", required=False) # 通过 --digit xxx 声明的参数，为int类型
args = parser.parse_args()
f_name = args.name


print(f"当前入口函数名称为:{f_name}")

def package_extract():
    '''
    这边主要是将模块 导出出来
    :return:
    '''
    print("ST2:模块文件分离开始...")
    module_list = []
    for i in os.listdir("pyd"):
        if i.endswith(".py"):
            with open("pyd/" + i, "r", encoding='utf8') as f:
                source_list = f.read().split('\n')
                temp_code_list = []
                for s in source_list:
                    if s.startswith("import "):
                        module_list.append(s)
                    elif s.startswith("from "):
                        if re.findall("from(.*?)import", s)[0].strip() + ".py" not in os.listdir("pyd"):
                            module_list.append(s)
                        else:
                            temp_code_list.append(s)
                    else:
                        temp_code_list.append(s)

            for index, cc in enumerate(temp_code_list):
                if cc.startswith("#") or cc.startswith('"') or cc.startswith("'") or len(cc) <= 2:
                    continue
                else:
                    temp_code_list.insert(index, "from module_import import *\n")
                    break

            with open("pyd/" + i, 'w', encoding='utf8') as fm:
                fm.write("\n".join(temp_code_list))

    module_list = list(set(module_list))
    module_list.insert(0, '# -*-coding:utf-8 -*-')

    with open("pyd/module_import.py", 'w', encoding='utf8') as f:
        f.write("\n".join(module_list))

    print("ST2:模块文件分离成功")


def make_pyd():
    pyd_list = []
    for i in os.listdir("pyd"):
        if i.endswith(".py") and i != "module_import.py":
            pyd_list.append(i)

    mess = f'''
from distutils.core import setup
from Cython.Build import cythonize

setup(
    name='any words.....',
    ext_modules=cythonize({pyd_list}
                          ),
    )                
            
    
    '''

    with open("pyd/build_pyd.py", 'w', encoding='utf8') as f:
        f.write(mess)

    os.system("cd pyd && python build_pyd.py build_ext --inplace")


def make_exe(name):
    mess = f'''
from {name} import start  
start()
    '''
    with open(f"pyd/{name}.py", 'r', encoding='utf8') as f:
        con = f.read()

    if "def start()" not in con:
        print("未找到入口函数:start() ,请修改代码在试！")
        return

    #cmd 命令拼接...
    module_import_list = []
    for i in os.listdir("pyd"):
        if i != "build_pyd.py" and i.endswith(".py"):
            module_import_list.append(i.replace(".py", ""))

    with open(f"pyd/{name}_main.py", 'w', encoding='utf8') as f:
        f.write(mess)

    cmd = f"cd pyd && pyinstaller -F -c {name}_main.py --hidden-import {' --hidden-import '.join(module_import_list)}"
    print(cmd)
    os.system(cmd)


def start(filename):

    if not os.path.exists("pyd"):
        os.mkdir("pyd")
    else:
        shutil.rmtree('./pyd')
        os.mkdir("pyd")


    #文件的一个复制
    print("ST1:文件复制开始....")

    for i in os.listdir():
        if i.endswith(".py") and i != "pydexe.py":
            shutil.copy(i, 'pyd/' + i)

    print("ST1:文件复制开始完成！")
    package_extract()
    print("ST3:pyd文件创建开始....")
    make_pyd()
    print("ST3:pyd文件创建成功！")
    print("ST4:exe文件创建开始....")
    filename = filename.replace(".py", "")
    filename = filename.replace('.\\', "")
    print(filename)
    filename = filename.replace(r'./', "")

    make_exe(filename)
    print("ST4:exe文件创建完成！")


def environment_init():
    #判断库文件是否存在
    print("****环境初始化开始*****")
    res = os.popen('pip list', 'r')
    con = str(res.read())
    res.close()

    if "Cython" not in con:
        os.system("pip install Cython")

    if "pyinstaller " not in con and "pyinstaller-hooks-contrib" not in con:
        os.system("pip install pyinstaller")

    if "tinyaes" not in con:
        os.system("pip install tinyaes")

    print("----环境初始化完成----")


if __name__ == '__main__':
    environment_init()
    start(f_name)
